/*
* Copyright 2011 Stepan Riha
*
* This file may be used under the terms of of the
* GNU General Public License Version 3 or later (the "GPL"),
* http://www.gnu.org/licenses/gpl.html
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*/


var BB = (function() {

	// Sort site data by title
	stores.sort(compareByTitle);

	// Create lookup tables

	function getStores(includeInactive) {
		var sites = [];
		for(var i = 0; i < stores.length; i++) {
			var site = new Store(stores[i]);
			if(includeInactive || site.active()) {
				sites.push(site);
			}
		}
		return sites;
	}
	
	function processActiveLibraries(cb) {
		Database.getLibraries(function(libraries) {
			Database.getCustomLibraries(function(custom) {
				cb(libraries.concat(custom));
			});
		 });
	}
	
	function compareByTitle(a, b) {
		if(a.title < b.title) return -1;
		if(a.title > b.title) return 1;
		return 0;
	}
	
	function getSite(site, cb) {
		var name = site.name;
		if(site.kind == 'libraries') {
			Database.getLibraryByName(name, cb);
		} else if(site.kind == 'custom') {
			Database.getCustomLibraryByName(name, cb);
		} else {
			var sites = getStores();
			
			for(var i = 0; i < sites.length; i++) {
				if(sites[i].name == name) {
					if(cb) {
						cb(sites[i]);
					}
					return sites[i];
				}
			}
		}
	}
	
	return {
		version: "0.9.2",
		stores: getStores(true),
		get_active_stores: function() { return getStores(false) },
		process_active_libraries: function(cb) { return processActiveLibraries(cb) },
		getSite : getSite
	}
	
}());